package z1mongo

import (
	"context"
	"time"

	"gitee.com/z1gotool/z1err"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

var DB *mongo.Database

// connetc pool
// url	mongodb://localhost:27017, mongodb://username:password@localhost:27017
func Connect(uri, dbName string, timeout, clientMaxNum uint64) (db *mongo.Database, err error) {
	defer z1err.Handle(&err)

	// https://zhuanlan.zhihu.com/p/613226112
	// 设置连接超时时间
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout*uint64(time.Second)))
	defer cancel()
	// 通过传进来的uri连接相关的配置
	opts := options.Client().ApplyURI(uri)
	// 设置最大连接数 - 默认是100 ，不设置就是最大 max 64
	opts.SetMaxPoolSize(clientMaxNum)
	// 发起链接
	client, err := mongo.Connect(ctx, opts)
	z1err.Check(err)
	// 判断服务是不是可用
	err = client.Ping(context.Background(), readpref.Primary())
	z1err.Check(err)
	// 返回 client
	db = client.Database(dbName)

	DB = db

	return
}

func Disconnect(db *mongo.Database) (err error) {
	defer z1err.Handle(&err)

	if db != nil {
		err = db.Client().Disconnect(context.Background())
		z1err.Check(err)
	}

	return
}
